﻿using Furion;
using Furion.DependencyInjection;
using Furion.DependencyInjection.Extensions;
using Microsoft.Extensions.DependencyInjection;
using NewLife.MQTT;
using Queer.Mqtt.Core.Entity;
using Queer.Mqtt.Core.Model;
using Queer.Mqtt.Core.Service;
using Queer.Mqtt.Job;
using Queer.Util.Helper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Queer.Mqtt
{
    public class MqttClientCenter : ISingleton
    {
        private static MqttClient _mqttClient;
        private static MqttClient mqttClient
        {
            get
            {
                if (_mqttClient == null)
                {
                    _mqttClient = new MqttClient
                    {
                        Server = $"tcp://{mqttConfig.MqttTcpServer}:{mqttConfig.MqttTcpHost}",
                        UserName = mqttConfig.MqttUserName,
                        Password = mqttConfig.MqttPasswrod,
                        ClientId = Guid.NewGuid() + ""
                    };
                }
                return _mqttClient;
            }
        }

        /// <summary>
        /// MQTT配置
        /// </summary>
        private static MqttConfig mqttConfig
        {
            get
            {
                return App.GetOptions<MqttConfig>();
            }
        }

        /// <summary>
        /// 打开连接并订阅配置主题
        /// </summary>
        public static async Task OpenConnectAsync()
        {
            try
            {
                // 配置关闭了的话，就不再执行了
                if (mqttConfig.MqttIsOpen == false)
                    return;

                // 查询所需订阅的主题
                var serviceScopeFactory = App.GetService<IServiceScopeFactory>();

                List<MqttThemeEntity> themes;
                using (var scope = serviceScopeFactory.CreateScope())
                {
                    var service = scope.ServiceProvider;
                    var mqttThemeBll = service.GetService<IMqttThemeService>();
                    themes = await mqttThemeBll.GetList(new MqttThemeListParam() { IsSubscribe = true });
                }

                // 创建连接
                await mqttClient.ConnectAsync();

                // 批量订阅配置的主题
                foreach (var topic in themes)
                    await Subscribe(topic.ThemeName);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }

        /// <summary>
        /// 订阅主题
        /// </summary>
        public static async Task Subscribe(string topic)
        {
            await _mqttClient.SubscribeAsync(topic, async (e) =>
            {
                var serviceScopeFactory = App.GetService<IServiceScopeFactory>();

                using (var scope = serviceScopeFactory.CreateScope())
                {
                    var service = scope.ServiceProvider;

                    // 记录日志（采用sqlsugar）
                    var sqlsugar = service.GetService<ISqlSugarRepository<MqttMsgEntity>>();
                    var entity = new MqttMsgEntity()
                    {
                        Id = IdGeneratorHelper.Instance.GetId(),
                        Msg = e.Payload.ToStr(),
                        ThemeName = e.Topic,
                        Time = DateTime.Now
                    };
                    await sqlsugar.InsertAsync(entity);

                    // 具体执行任务
                    switch (e.Topic)
                    {
                        case "Test":
                            await service.GetService<MqttWorkTest>().DoWork(e.Payload.ToStr());
                            break;

                        default:
                            LogHelper.Error("MQTT未设定相应主题执行业务！主题：" + topic);
                            break;
                    }
                }
            });
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        public static async Task Unsubscribe(params string[] topic)
        {
            await _mqttClient.UnsubscribeAsync(topic);
        }

    }
}